#!/usr/bin/env bash

include "replace.sh"

# variable: loop_mesg_map_*
# variable: loop_func_map_*
# variable: loop_prefunc
# variable: loop_command

# Loop::Register key mesg func
function Loop::Register()
{
    local key="$1"; shift
    local mesg="$1"; shift

    eval "loop_mesg_map_$key=\"$mesg\""
    eval "loop_func_map_$key=\"$@\""
}

# Loop::Register prefunc
function Loop::RegisterPre()
{
    loop_prefunc="$@"
}

function Loop::EditSelf()
{
    vim $0 && source $0
}

function Loop::LastCommand()
{
    echo "$loop_command"
}

function Loop::Start()
{
    while true; do
        $loop_prefunc

        if ! read loop_command; then
            break
        fi
        loop_command+=";"

        if [ "${loop_command%%;*}" == "" ]; then
            declare | egrep "^loop_mesg_map_[a-zA-Z0-9]*=" | Replace "
                <^loop_mesg_map_>
                <>

                <=>
                <: >

                <'>
                <>
                :g
            "
        fi

        while [ "${loop_command%%;*}" != "" ]; do
            local command="loop_func_map_${loop_command%%;*}"
            local func="${!command}"
            call $func
            loop_command="${loop_command#*;}"
        done
    done
}
